package com.sinogrand.elevator.ui.components

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.*
import androidx.compose.material3.*
import androidx.compose.material3.pulltorefresh.PullToRefreshContainer
import androidx.compose.material3.pulltorefresh.rememberPullToRefreshState
import androidx.compose.runtime.*
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.zIndex
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import androidx.compose.runtime.rememberCoroutineScope
import coil.compose.AsyncImage
import androidx.compose.ui.layout.ContentScale
import com.sinogrand.elevator.utils.PaginationUtils
import com.sinogrand.elevator.data.models.PageInfo
import com.sinogrand.elevator.data.models.ProjectUserItem as ApiProjectUserItem
import com.sinogrand.elevator.repository.ProjectUserRepository
import androidx.compose.ui.platform.LocalContext
import android.util.Log
import com.sinogrand.elevator.utils.LogTags

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun MemberListTab(
    project: ProjectItem
) {
    val context = LocalContext.current
    val projectUserRepository = remember { ProjectUserRepository(context) }
    
    var isRefreshing by rememberSaveable { mutableStateOf(false) }
    var isLoadingMore by rememberSaveable { mutableStateOf(false) }
    var canLoadMore by rememberSaveable { mutableStateOf(true) }
    var currentPage by rememberSaveable { mutableStateOf(1) }
    var searchQuery by rememberSaveable { mutableStateOf("") }
    var isSearching by rememberSaveable { mutableStateOf(false) }
    var isLoading by rememberSaveable { mutableStateOf(true) }
    var errorMessage by rememberSaveable { mutableStateOf<String?>(null) }
    
    // 使用 rememberSaveable 保持滚动状态
    val listState = rememberSaveable(saver = LazyListState.Saver) {
        LazyListState()
    }
    val pullRefreshState = rememberPullToRefreshState()
    val coroutineScope = rememberCoroutineScope()
    
    // 用户数据
    var users by rememberSaveable { mutableStateOf<List<ApiProjectUserItem>>(emptyList()) }
    var currentPageInfo by rememberSaveable { mutableStateOf<PageInfo?>(null) }
    
    // 加载用户数据
    suspend fun loadUsers(page: Int = 1, searchName: String? = null, isRefresh: Boolean = false) {
        try {
            Log.d(LogTags.PROJECT_USER_LIST, "开始加载项目用户数据，项目ID: ${project.id}, 页码: $page")
            if (isRefresh) {
                isRefreshing = true
            } else if (page == 1) {
                isLoading = true
            } else {
                isLoadingMore = true
            }
            errorMessage = null

            val result = projectUserRepository.getProjectUserList(
                projectId = project.id.toInt(),
                page = page,
                size = 10,
                name = searchName
            )
            
            if (result.isSuccess) {
                val data = result.getOrNull()
                if (data != null) {
                    if (isRefresh || page == 1) {
                        users = data.list
                        currentPage = 1
                        currentPageInfo = data.page_info
                        canLoadMore = PaginationUtils.hasNextPage(data.page_info)
                        Log.i(LogTags.PROJECT_USER_LIST, "✅ 成功加载用户数据: ${data.list.size}条，分页信息: page=${data.page_info.page}, size=${data.page_info.size}, total=${data.page_info.total}")
                    } else {
                        users = users + data.list
                        currentPageInfo = data.page_info
                        canLoadMore = PaginationUtils.hasNextPage(data.page_info)
                        Log.i(LogTags.PROJECT_USER_LIST, "✅ 成功加载更多用户数据: ${data.list.size}条，累计: ${users.size}条，分页信息: page=${data.page_info.page}, size=${data.page_info.size}, total=${data.page_info.total}")
                    }
                } else {
                    Log.w(LogTags.PROJECT_USER_LIST, "⚠️ 用户数据为空")
                    errorMessage = "暂无用户数据"
                }
            } else {
                val error = result.exceptionOrNull()
                Log.e(LogTags.PROJECT_USER_LIST, "❌ 加载用户数据失败: ${error?.message}", error)
                errorMessage = error?.message ?: "加载用户数据失败"
            }
        } catch (e: Exception) {
            Log.e(LogTags.PROJECT_USER_LIST, "❌ 加载用户数据异常: ${e.message}", e)
            errorMessage = e.message ?: "加载用户数据异常"
        } finally {
            isLoading = false
            isRefreshing = false
            isLoadingMore = false
        }
    }
    
    // 处理加载更多
    fun handleLoadMore() {
        if (canLoadMore && !isLoadingMore) {
            currentPage++
            coroutineScope.launch {
                loadUsers(currentPage, if (searchQuery.isBlank()) null else searchQuery)
            }
        }
    }
    
    // 处理搜索
    fun handleSearch(query: String) {
        searchQuery = query
        isSearching = true
        coroutineScope.launch {
            delay(300) // 防抖延迟
            loadUsers(1, if (query.isBlank()) null else query)
            isSearching = false
        }
    }
    
    // 处理刷新
    fun handleRefresh() {
        coroutineScope.launch {
            loadUsers(1, if (searchQuery.isBlank()) null else searchQuery, isRefresh = true)
        }
    }
    
    // 初始化加载
    LaunchedEffect(project.id) {
        loadUsers()
    }
    
    // 下拉刷新
    if (pullRefreshState.isRefreshing) {
        LaunchedEffect(true) {
            handleRefresh()
            pullRefreshState.endRefresh()
        }
    }
    
    // 上拉加载更多
    LaunchedEffect(listState) {
        snapshotFlow { listState.layoutInfo.visibleItemsInfo.lastOrNull()?.index }
            .collect { lastVisibleIndex ->
                if (lastVisibleIndex != null && 
                    lastVisibleIndex >= users.size - 1 && 
                    canLoadMore && 
                    !isLoadingMore &&
                    users.isNotEmpty()) {
                    handleLoadMore()
                }
            }
    }
    
    Box(
        modifier = Modifier
            .fillMaxSize()
            .nestedScroll(pullRefreshState.nestedScrollConnection)
    ) {
        Column {
            // 搜索框
            SearchBar(
                query = searchQuery,
                onQueryChange = { searchQuery = it },
                onSearch = { handleSearch(searchQuery) },
                onClear = {
                    searchQuery = ""
                    handleSearch("")
                },
                placeholder = "搜索姓名",
                isSearching = isSearching,
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(16.dp)
                    .height(48.dp)
            )
            
            // 用户列表
            LazyColumn(
                state = listState,
                modifier = Modifier
                    .fillMaxSize()
                    .padding(horizontal = 16.dp),
                verticalArrangement = Arrangement.spacedBy(8.dp),
                contentPadding = PaddingValues(
                    top = 8.dp,
                    bottom = 16.dp
                )
            ) {
                // 加载状态 - 只在没有数据时显示
                if (isLoading && users.isEmpty()) {
                    item {
                        LoadingIndicator()
                    }
                }
                
                // 错误信息
                errorMessage?.let { message ->
                    item {
                        Card(
                            modifier = Modifier.fillMaxWidth(),
                            colors = CardDefaults.cardColors(
                                containerColor = Color(0xFFFEF2F2)
                            ),
                            elevation = CardDefaults.cardElevation(defaultElevation = 2.dp),
                            shape = RoundedCornerShape(12.dp)
                        ) {
                            Text(
                                text = message,
                                fontSize = 14.sp,
                                color = Color(0xFFDC2626),
                                modifier = Modifier.padding(16.dp)
                            )
                        }
                    }
                }
                
                if (users.isEmpty() && !isLoading) {
                    item {
                        EmptyState(
                            title = if (errorMessage != null) "加载失败" else "暂无组员",
                            description = if (errorMessage != null) "请检查网络连接后重试" else "当前项目还没有组员数据"
                        )
                    }
                } else {
                    items(users.size) { index ->
                        val user = users[index]
                        MemberItemCard(
                            user = user
                        )
                    }
                }
                
                // 加载更多指示器
                if (isLoadingMore) {
                    item {
                        LoadingIndicator()
                    }
                }
                
                // 没有更多数据提示
                if (!canLoadMore && users.isNotEmpty()) {
                    item {
                        NoMoreDataIndicator()
                    }
                }
            }
        }
        
        // 下拉刷新容器 - 只在需要时显示
        if (pullRefreshState.isRefreshing || pullRefreshState.progress > 0f) {
            PullToRefreshContainer(
                state = pullRefreshState,
                modifier = Modifier
                    .align(Alignment.TopCenter)
                    .zIndex(1f) // 确保在列表内容之上
            )
        }
    }
}

@Composable
fun MemberItemCard(
    user: ApiProjectUserItem
) {
    Card(
        modifier = Modifier.fillMaxWidth(),
        colors = CardDefaults.cardColors(
            containerColor = Color.White
        ),
        elevation = CardDefaults.cardElevation(
            defaultElevation = 2.dp
        ),
        shape = RoundedCornerShape(12.dp)
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            // 头像
            Box(
                modifier = Modifier
                    .size(50.dp)
                    .clip(CircleShape)
                    .background(Color(0xFFF3F4F6)),
                contentAlignment = Alignment.Center
            ) {
                if (user.avatar != null) {
                    AsyncImage(
                        model = user.avatar,
                        contentDescription = null,
                        modifier = Modifier
                            .fillMaxSize()
                            .clip(CircleShape),
                        contentScale = ContentScale.Crop
                    )
                } else {
                    Icon(
                        imageVector = Icons.Default.Person,
                        contentDescription = null,
                        modifier = Modifier.size(24.dp),
                        tint = Color(0xFF9CA3AF)
                    )
                }
            }
            
            Spacer(modifier = Modifier.width(12.dp))
            
            // 用户信息
            Column(
                modifier = Modifier.weight(1f)
            ) {
                Text(
                    text = user.real_name,
                    fontSize = 16.sp,
                    fontWeight = FontWeight.Bold,
                    color = Color(0xFF1F2937),
                    maxLines = 1,
                    overflow = TextOverflow.Ellipsis
                )
                
                Spacer(modifier = Modifier.height(4.dp))
                
                Text(
                    text = user.mobile,
                    fontSize = 14.sp,
                    color = Color(0xFF6B7280),
                    maxLines = 1,
                    overflow = TextOverflow.Ellipsis
                )
            }
        }
    }
}
